extends Area2D

var isActivated: bool
var sprite
@export var level: int = -1  # `-1` means ignore leveling
@onready var animation_player: AnimationPlayer = $AnimationPlayer

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	add_to_group("check_points")
	sprite = $AnimatedSprite2D
	isActivated = false
	sprite.modulate.a = 0


func _on_body_entered(body: Node2D) -> void:
	var latest_name = GlobalGameData.playerRespawnPoints[-1].name
	if body.name == "Player" and latest_name != name:
		await body.isOnFloor
		var respawnPoint = global_position
		GlobalGameData.playerRespawnPoints.append({
			pos=respawnPoint,
			name=name,
		})
		if level > 0: GlobalGameData.reach_level(level)
	Game.update_checkpoints.emit()


func update_state() -> void:
	if GlobalGameData.playerRespawnPoints:
		var last := GlobalGameData.playerRespawnPoints[-2].name as String
		var current := GlobalGameData.playerRespawnPoints[-1].name as String
		if last == name and current != name and isActivated:
			animation_player.play("unactivate")
			isActivated = false
		if last != name and current == name and not isActivated:
			animation_player.play("activate")
			isActivated = true
